const state = {
  availableModules: [
    {
      id: 'http-client',
      name: 'HTTP客户端',
      icon: 'el-icon-upload2',
      description: '发送HTTP请求并查看响应',
      enabled: true
    },
    {
      id: 'http-server',
      name: 'HTTP服务器',
      icon: 'el-icon-download',
      description: '创建本地HTTP服务器',
      enabled: true
    },
    {
      id: 'mqtt-client',
      name: 'MQTT客户端',
      icon: 'el-icon-message',
      description: 'MQTT协议客户端',
      enabled: true
    },
    {
      id: 'websocket',
      name: 'WebSocket',
      icon: 'el-icon-refresh',
      description: 'WebSocket连接测试',
      enabled: true
    },
    {
      id: 'tcp-udp',
      name: 'TCP/UDP',
      icon: 'el-icon-share',
      description: 'TCP/UDP协议测试',
      enabled: true
    }
  ],
  loadedModules: {},
  activeModule: null
}

const mutations = {
  SET_MODULE_LOADED(state, { moduleId, loaded }) {
    state.loadedModules[moduleId] = loaded
  },
  
  SET_ACTIVE_MODULE(state, moduleId) {
    state.activeModule = moduleId
  },
  
  UPDATE_MODULE_STATUS(state, { moduleId, enabled }) {
    const module = state.availableModules.find(m => m.id === moduleId)
    if (module) {
      module.enabled = enabled
    }
  }
}

const actions = {
  async loadModule({ commit, dispatch }, moudleInfo) {
    commit('SET_ACTIVE_MODULE', moudleInfo.moduleId)
    
    if (!state.loadedModules[moudleInfo.moduleId]) {
      dispatch('ui/showLoading', `正在加载 ${moudleInfo.moduleId} 模块...`, { root: true })
      
      setTimeout(() => {
        commit('SET_MODULE_LOADED', { moduleId:moudleInfo.moduleId, loaded: true })
        dispatch('ui/hideLoading', null, { root: true })
      }, 300)
    }
    
    dispatch('ui/addTab', {
      id: moudleInfo.moduleId,
      title: state.availableModules.find(m => m.id === moudleInfo.moduleId)?.name || moudleInfo.title || moudleInfo.moduleId,
      route: `/${moudleInfo.moduleId}`
    }, { root: true })
  },
  
  openModule({ dispatch }, moduleId) {
    dispatch('loadModule', moduleId)
  },
  
  toggleModuleStatus({ commit }, { moduleId, enabled }) {
    commit('UPDATE_MODULE_STATUS', { moduleId, enabled })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}